package com.mango.request;

import android.support.annotation.Nullable;

import com.mango.request.beans.ConfigBean;
import com.mango.request.beans.ConfigBean.CommonBean;
import com.mango.request.beans.ConfigBean.PosInfoBean;
import com.mango.volley.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ReqMgConfig extends ReqMango<ConfigBean> {
    public ReqMgConfig(String appID, String appKey,
                       @Nullable Response.Listener<ConfigBean> listener,
                       @Nullable Response.ErrorListener errorListener) {
        super("api/ad/config", new Object[]{"appId", appID, null, appKey,
                "timeStamp", System.currentTimeMillis()}, listener, errorListener);
    }

    @Override
    protected String getJsonParams() {
        return null;
    }

    @Override
    protected ConfigBean parseJsonResult(String json) throws JSONException {
        JSONObject data = new JSONObject(json).getJSONObject("data");

        JSONObject comm = data.getJSONObject("comm");
        JSONArray sdks = data.getJSONArray("sdks");

        ConfigBean result = new ConfigBean();

        result.comm = new CommonBean();
        result.comm.shake = comm.optInt("shake");
        result.comm.clkGrade = comm.optInt("clkGrade");
        result.comm.autoWake = comm.optInt("autoWake");
        result.comm.downSecond = comm.optInt("downSecond");
        result.comm.deeplinkSecond = comm.optInt("deeplinkSecond");
        result.comm.integralName = comm.optString("integralName");
        result.comm.integralIcon = comm.optString("integralIcon");

        result.platforms = new HashMap<>();
        result.positions = new HashMap<>();

        final int size = sdks.length();
        for (int i = 0; i < size; i++) {
            JSONObject sdk = sdks.optJSONObject(i);
            if (sdk == null) continue;

            PosInfoBean item = new PosInfoBean();
            item.sdkId = sdk.optInt("sdkId");
            item.type = sdk.optInt("type");
            item.adType = sdk.optInt("adType");

            item.mgPosId = sdk.optString("mgPosId");
            item.requestUrl = sdk.optString("requestUrl");

            item.weight = sdk.optInt("weight");
            item.eCPM = sdk.optInt("eCPM");

            item.appId = sdk.optString("appId");
            item.appKey = sdk.optString("appKey");
            item.posId = sdk.optString("posId");
            item.packageName = sdk.optString("packageName");

            if (!result.platforms.containsKey(item.type)) result.platforms
                    .put(item.type, new String[]{item.appId, item.appKey});

            List<PosInfoBean> list = result.positions.get(item.mgPosId);
            if (list == null) result.positions.put(item.mgPosId,
                    list = new ArrayList<>());
            list.add(item);
        }

        return result;
    }
}
